﻿using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Utils;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DepartmentWork.Platform.Areas.DepartmentArea.Controllers
{
    /// <summary>
    /// 请假模块
    /// </summary>
    public class LeaveController : BaseController
    {






        /// <summary>
        /// 个人请假列表/全部人员请假
        /// </summary>
        /// <returns></returns>
        public ActionResult Leave(string flag = "", string flagInfo = "")
        {

            #region 设置分页

            var pageSizeExecute = this.Request["pageSizeExecute"] == null ? 10 : int.Parse(Request["pageSizeExecute"]);
            var pageIndexExecute = this.Request["pageIndexExecute"] == null ? 1 : int.Parse(Request["pageIndexExecute"]);

            ViewData["pageIndexExecute"] = pageIndexExecute;//1
            ViewData["pageSizeExecute"] = pageSizeExecute;//10

            var pageSize = this.Request["pageSizeFinish"] == null ? 10 : int.Parse(Request["pageSizeFinish"]);
            var pageIndex = this.Request["pageIndexFinish"] == null ? 1 : int.Parse(Request["pageIndexFinish"]);

            ViewData["pageIndexFinish"] = pageIndex;//1
            ViewData["pageSizeFinish"] = pageSize;//10


            var pageB = this.Request["pageSizeB"] == null ? 10 : int.Parse(Request["pageSizeB"]);
            var pageD = this.Request["pageIndexD"] == null ? 1 : int.Parse(Request["pageIndexD"]);

            ViewData["pageIndexD"] = pageD;//1
            ViewData["pageSizeB"] = pageB;//10
            #endregion

            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;

            List<PROJECT_DESK_LEAVE> OwnLeave = new List<PROJECT_DESK_LEAVE>();//自己请假
            List<PROJECT_DESK_LEAVE> AllLeave = new List<PROJECT_DESK_LEAVE>();//全体请假
            List<ProjectDeskLeaveViewModel> ViewAllLeave = new List<ProjectDeskLeaveViewModel>();//全体请假
            List<ProjectDeskLeaveViewModel> ViewOwnLeave = new List<ProjectDeskLeaveViewModel>();//自己请假
            List<PROJECT_DESK_LEAVE> DAI = new List<PROJECT_DESK_LEAVE>();//待审批
            List<ProjectDeskLeaveViewModel> dai = new List<ProjectDeskLeaveViewModel>();//自己请假
            #region 若不是匿名用户则读取该用户所在的团队空间项目；如果是匿名用户则读取所有团队空间的项目
            if (CurrentUser.UserID.Length != 0)//如果数据库中存在这个用户，说明这个用户是科室人员
            {
                //根据登录ID找到团队空间ID
                Guid teamSpaceId = userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID)).FirstOrDefault().TEAMSPACE_ID;
                OwnLeave = projectdeskleaveRepository.GetModel(r => r.Leave_NAMEID == new Guid(CurrentUser.UserID)).OrderByDescending(r => r.LEAVE_TIME).ToList();//个人请假信息
                for (int i = 0; i < OwnLeave.Count; i++)
                {
                    Guid id = OwnLeave[i].Leave_NAMEID;
                    var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();//要权限
                    ProjectDeskLeaveViewModel viewmodel = new ProjectDeskLeaveViewModel();
                    viewmodel.leave_id = OwnLeave[i].LEAVE_ID;
                    viewmodel.leave_name = username;
                    viewmodel.Leave_nameid = OwnLeave[i].Leave_NAMEID;
                    viewmodel.leave_cause = OwnLeave[i].LEAVE_CAUSE;
                    viewmodel.leave_classes = OwnLeave[i].LEAVE_CLASSES;
                    viewmodel.leave_approverresult = OwnLeave[i].LEAVE_APPROVERRESULT;
                    viewmodel.leave_howmanydays = OwnLeave[i].LEAVE_HOWMANYDAYS;
                    viewmodel.leave_quantity = OwnLeave[i].LEAVE_QUANTITY;
                    viewmodel.leave_time = OwnLeave[i].LEAVE_TIME;
                    viewmodel.leave_approver = OwnLeave[i].LEAVE_APPROVER;
                    viewmodel.leave_day = OwnLeave[i].LEAVE_BEGAIN_DAY.ToString("yyyy-MM-dd") + "—" + OwnLeave[i].LEAVE_END_DAY.ToString("yyyy-MM-dd");
                    ViewOwnLeave.Add(viewmodel);//将所有自己的请假信息放入ViewOwnLeave中
                }
                Guid myid = new Guid(CurrentUser.UserID);
                var myname = userRepository.Find(r => r.USER_ID == myid).DISPLAY_NAME.ToString();//要权限
                ViewBag.myName = myname;//获取到登录人的姓名返回给界面用于锁定发布人
                #region 获取该团队空间下的全部人员
                List<UserInfoViewModel> userList = new List<UserInfoViewModel>();//实例化UserInfoViewModel
                //查询出数据库中团队空间ID和当前登录用户的团队ID相等的所有信息
                List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId).ToList();
                //根据查出空间团队想的所有信息，再查出所有人的用户ID，放进实例化的UserInfoViewModel表中
                userList.AddRange((from item in userTeams
                                   select new UserInfoViewModel()
                                       {
                                           UserId = item.USER_ID
                                       }).ToList());
                for (int i = 0; i < userList.Count(); i++)//遍历，每个ID所对应的员工姓名
                {
                    var id = userList[i].UserId;
                    userList[i].UserName = userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                }
                TempData["UserList"] = userList;

                for (int i = 0; i < userList.Count; i++)
                {
                    Guid id = userList[i].UserId;
                    AllLeave.AddRange(projectdeskleaveRepository.GetModel(r => r.Leave_NAMEID == id&&r.LEAVE_APPROVERRESULT=="1").OrderByDescending(r => r.LEAVE_TIME).ToList());
                }
                for (int i = 0; i < AllLeave.Count; i++)
                {
                    Guid id = AllLeave[i].Leave_NAMEID;
                    var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();   
                    ProjectDeskLeaveViewModel viewmodel = new ProjectDeskLeaveViewModel();
                    viewmodel.leave_id = AllLeave[i].LEAVE_ID;
                    viewmodel.leave_name = username;
                    viewmodel.Leave_nameid = AllLeave[i].Leave_NAMEID;
                    viewmodel.leave_cause = AllLeave[i].LEAVE_CAUSE;
                    viewmodel.leave_classes = AllLeave[i].LEAVE_CLASSES;
                    viewmodel.leave_approverresult = AllLeave[i].LEAVE_APPROVERRESULT;
                    viewmodel.leave_howmanydays = AllLeave[i].LEAVE_HOWMANYDAYS;
                    viewmodel.leave_quantity = AllLeave[i].LEAVE_QUANTITY;
                    viewmodel.leave_time = AllLeave[i].LEAVE_TIME;
                    viewmodel.leave_approver = AllLeave[i].LEAVE_APPROVER;
                    viewmodel.leave_day = AllLeave[i].LEAVE_BEGAIN_DAY.ToString("yyyy-MM-dd") + "—" + AllLeave[i].LEAVE_END_DAY.ToString("yyyy-MM-dd");
                    ViewAllLeave.Add(viewmodel);//将所有的人员的请假信息放入ViewAllLeave中
                }
                #endregion
                

                #region 获取该团队空间下的全部负责人
                List<UserInfoViewModel> LD = new List<UserInfoViewModel>();//实例化UserInfoViewModel
                //查询出数据库中团队空间ID和当前登录用户的团队ID相等的所有信息
                List<USER_TEAMSAPCE> UserTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId && r.ROLE_ID == 5).ToList();
                //根据查出空间团队想的所有信息，再查出所有人的用户ID，放进实例化的UserInfoViewModel表中
                LD.AddRange((from item in UserTeams
                                   select new UserInfoViewModel()
                                   {
                                       UserId = item.USER_ID
                                   }).ToList());
                for (int i = 0; i < LD.Count(); i++)//遍历，每个ID所对应的员工姓名
                {
                    var id = LD[i].UserId;
                    LD[i].UserName = userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                }
                TempData["User"] = LD;
              
                #endregion

                #region 登录人的待审批请假
            
                Guid overid = new Guid(CurrentUser.UserID);
                DAI = projectdeskleaveRepository.GetModel(r => r.LEAVE_OVERNAME == overid && r.LEAVE_APPROVERRESULT == "0").ToList();
                if (DAI.Count > 0)
                {
                    foreach (PROJECT_DESK_LEAVE over in DAI)
                    {
                        ProjectDeskLeaveViewModel MODEL = new ProjectDeskLeaveViewModel();

                        Guid DaiID = over.Leave_NAMEID;
                        var DaiName = userRepository.Find(r => r.USER_ID == DaiID).DISPLAY_NAME.ToString();//加班人姓名
                        MODEL.leave_howmanydays = over.LEAVE_HOWMANYDAYS;
                        MODEL.leave_name = DaiName;
                        MODEL.leave_time = over.LEAVE_TIME;
                        MODEL.leave_day = over.LEAVE_BEGAIN_DAY.ToString("yyyy-MM-dd") + "—" + over.LEAVE_END_DAY.ToString("yyyy-MM-dd");
                        MODEL.leave_classes = over.LEAVE_CLASSES;
                        MODEL.leave_id = over.LEAVE_ID;
                        dai.Add(MODEL);
                    }
                }

                #endregion

                #region 校验身份
                ViewBag.IsAdmin = false;
                string[] pathArr = Request.Path.Split('/');
                Guid userGuid = new Guid(CurrentUser.UserID);//找到用户登录ID
                USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();//根据用户登录ID 通过员工表 查出此员工信息
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();//根据员工的ID 通过团队空间表  查出此人的团队空间信息
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();//根据此人全队空间表信息的团队空间权限ID，查出此人在权限表的信息
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();//根据此人在权限表的信息中的权限ID，查出此人的菜单表信息
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();//根据菜单Id找此人菜单表的所有信息
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                    {
                        ViewBag.IsAdmin = true;
                        break;
                    }
                }
                #endregion
                ViewBag.anonymity = true;

            #endregion
            }
            else//如果是匿名用户
            {
                #region
                AllLeave = projectdeskleaveRepository.GetModel(r=>r.LEAVE_APPROVERRESULT=="1").OrderByDescending(r => r.LEAVE_TIME).ToList();
                for (int i = 0; i < AllLeave.Count; i++)
                {
                    Guid id = AllLeave[i].Leave_NAMEID;
                    var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();  //要权限
                    ProjectDeskLeaveViewModel viewmodel = new ProjectDeskLeaveViewModel();
                    viewmodel.leave_id = AllLeave[i].LEAVE_ID;
                    viewmodel.leave_name = username;//要权限后修改
                    viewmodel.Leave_nameid = AllLeave[i].Leave_NAMEID;
                    viewmodel.leave_cause = AllLeave[i].LEAVE_CAUSE;
                    viewmodel.leave_classes = AllLeave[i].LEAVE_CLASSES;
                    viewmodel.leave_approverresult = AllLeave[i].LEAVE_APPROVERRESULT;
                    viewmodel.leave_howmanydays = AllLeave[i].LEAVE_HOWMANYDAYS;
                    viewmodel.leave_quantity = AllLeave[i].LEAVE_QUANTITY;
                    viewmodel.leave_time = AllLeave[i].LEAVE_TIME;
                    viewmodel.leave_approver = AllLeave[i].LEAVE_APPROVER;
                    viewmodel.leave_day = AllLeave[i].LEAVE_BEGAIN_DAY.ToString("yyyy-MM-dd") + "—" + AllLeave[i].LEAVE_END_DAY.ToString("yyyy-MM-dd");
                    ViewAllLeave.Add(viewmodel);
                }
                ViewBag.anonymity = false;
                ViewBag.IsAdmin = true;
                #endregion
            }




            ViewBag.ownLeave = ViewOwnLeave;
            ViewBag.allLeave = ViewAllLeave;
            ViewBag.DAI = dai;
            ViewData["totalExecute"] = ViewOwnLeave.Count;//自己
            ViewData["totalFinish"] = ViewAllLeave.Count;//全部


            return View();//返回给视图
        }


        /// <summary>
        /// 请假申请
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyForLeave(FormCollection collection)
        {
            try
            {
              
                Guid myid = new Guid(collection["tb_leave_approver"]);
                string name = userRepository.GetModel(r => r.USER_ID == myid).FirstOrDefault().DISPLAY_NAME;
                PROJECT_DESK_LEAVE leave = new PROJECT_DESK_LEAVE();
                leave.LEAVE_ID = Guid.NewGuid();
                leave.Leave_NAMEID = new Guid(CurrentUser.UserID);
                leave.LEAVE_TIME = DateTime.Now;
                leave.LEAVE_HOWMANYDAYS = Convert.ToInt32(collection["tb_leave_howmanydays"]);
                leave.LEAVE_CLASSES = collection["select_leave_classes"];
                leave.LEAVE_CAUSE = collection["tb_leave_cause"];
                leave.LEAVE_APPROVER = name;
                leave.LEAVE_APPROVERRESULT = "0";
                leave.LEAVE_QUANTITY = 0;
                leave.LEAVE_BEGAIN_DAY =Convert.ToDateTime(collection["tb_BTime"]);
                leave.LEAVE_END_DAY = Convert.ToDateTime(collection["tb_DTime"]);
                leave.LEAVE_OVERNAME = myid;
                projectdeskleaveRepository.Insert(leave);
                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flagInfo = "申请成功！", flag = "True" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flag = "False", flagInfo = "申请失败！" + ex.Message });
            }

        }


        /// <summary>
        /// 修改请假
        /// </summary> 
        /// <returns></returns>
        public ActionResult updat_Leave(FormCollection collection)
        {
            PROJECT_DESK_LEAVE model = new PROJECT_DESK_LEAVE();
            model.LEAVE_ID = new Guid(collection["td_leavet_id"]);
            PROJECT_DESK_LEAVE old = projectdeskleaveRepository.GetModel(r => r.LEAVE_ID == model.LEAVE_ID).FirstOrDefault();
            Guid myid = new Guid(collection["q_leave_approver"]);
            string name = userRepository.GetModel(r => r.USER_ID == myid).FirstOrDefault().DISPLAY_NAME;
            try
            {
                model.LEAVE_CAUSE = collection["q_leave_cause"] == "" ? old.LEAVE_CAUSE : collection["q_leave_cause"];
                model.LEAVE_APPROVER = name == "" ? old.LEAVE_APPROVER : name;
                model.LEAVE_APPROVERRESULT = old.LEAVE_APPROVERRESULT;
                model.LEAVE_CLASSES = collection["q_select_leave_classes"] == "" ? old.LEAVE_CLASSES : collection["q_select_leave_classes"];
                model.LEAVE_HOWMANYDAYS = collection["q_leave_howmanydays"] == "" ? old.LEAVE_HOWMANYDAYS : Convert.ToInt32(collection["q_leave_howmanydays"]);
                model.LEAVE_QUANTITY = old.LEAVE_QUANTITY;
                model.Leave_NAMEID = old.Leave_NAMEID;
                model.LEAVE_TIME = old.LEAVE_TIME;
                model.LEAVE_BEGAIN_DAY = collection["tb_BTime"] == "" ? old.LEAVE_BEGAIN_DAY : Convert.ToDateTime(collection["tb_BTime"]);
                model.LEAVE_END_DAY = collection["tb_DTime"] == "" ? old.LEAVE_END_DAY : Convert.ToDateTime(collection["tb_DTime"]);
                model.LEAVE_OVERNAME = myid;
                projectdeskleaveRepository.Update(model);
                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flagInfo = "修改成功！", flag = "True" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flag = "False", flagInfo = "修改失败！" + ex.Message });
            }
        }


        /// <summary>
        /// 删除请假
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult delete_Leave(FormCollection collection)
        {

            try
            {
                PROJECT_DESK_LEAVE model = new PROJECT_DESK_LEAVE();
                model.LEAVE_ID = new Guid(collection["delete_worktime_idd"]);

                PROJECT_DESK_LEAVE delete = projectdeskleaveRepository.GetModel(r => r.LEAVE_ID == model.LEAVE_ID).FirstOrDefault(); //被删除的加班记录
                List<PROJECT_DESK_LEAVE> LIST = new List<PROJECT_DESK_LEAVE>(); //删除后，要被修改的记录集合


                //被删除记录那个月的最后一天  并找出删除记录的那个月中大于被删除的加班记录小于那个月最后一天的加班记录(这个记录之后的要变的)
                DateTime timeZH = Convert.ToDateTime(delete.LEAVE_TIME.Year + "-" + delete.LEAVE_TIME.Month + "-" + DateTime.DaysInMonth(delete.LEAVE_TIME.Year, delete.LEAVE_TIME.Month));
                List<PROJECT_DESK_LEAVE> updatZH = projectdeskleaveRepository.GetModel(r => r.Leave_NAMEID == delete.Leave_NAMEID && r.LEAVE_TIME > delete.LEAVE_TIME && r.LEAVE_TIME <= timeZH).OrderBy(r => r.LEAVE_TIME).ToList();
                //被删除记录的那个月的第一天    并找出删除记录的那个月中小于被删除的加班记录大于那个月第一天的加班记录(之前不变的)
                DateTime timeZQ = Convert.ToDateTime(delete.LEAVE_TIME.Year + "-" + delete.LEAVE_TIME.Month + "-" + 1);
                List<PROJECT_DESK_LEAVE> updatZQ = projectdeskleaveRepository.GetModel(r => r.Leave_NAMEID == delete.Leave_NAMEID && r.LEAVE_TIME > timeZQ && r.LEAVE_TIME < delete.LEAVE_TIME).ToList();

                int cishu = updatZQ.Count;
                if (updatZH.Count > 0)
                {
                    foreach (PROJECT_DESK_LEAVE y in updatZH)
                    {
                        PROJECT_DESK_LEAVE list = new PROJECT_DESK_LEAVE();
                        list.LEAVE_CAUSE = y.LEAVE_CAUSE;
                        list.LEAVE_APPROVER = y.LEAVE_APPROVER;
                        list.LEAVE_APPROVERRESULT = y.LEAVE_APPROVERRESULT;
                        list.LEAVE_CLASSES = y.LEAVE_CLASSES;
                        list.LEAVE_HOWMANYDAYS = y.LEAVE_HOWMANYDAYS;
                        list.LEAVE_QUANTITY = cishu + 1;
                        cishu = cishu + 1;
                        list.LEAVE_ID = y.LEAVE_ID;
                        list.Leave_NAMEID = y.Leave_NAMEID;
                        list.LEAVE_TIME = y.LEAVE_TIME;
                        LIST.Add(list);
                    }
                }
                projectdeskleaveRepository.Delete(delete);
                projectdeskleaveRepository.Update(LIST);

                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flagInfo = "删除成功！", flag = "True" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flag = "False", flagInfo = "删除失败！" + ex.Message });
            }
        }



        /// <summary>
        /// 原版审批详情界面 
        /// </summary>
        /// <returns></returns>
        public ActionResult Examine_Leave(FormCollection collection)
        {
            #region 获得工作的基本信息

            Guid leaveGuid = new Guid(collection["dai_leave_idd"]);
            PROJECT_DESK_LEAVE leave = projectdeskleaveRepository.GetModel(r => r.LEAVE_ID == leaveGuid).FirstOrDefault();//判断传进来的ID是否和当前ID一致
            Guid id = leave.Leave_NAMEID;
            var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();//要权限
            ProjectDeskLeaveViewModel model = new ProjectDeskLeaveViewModel();
            {
                model.leave_id = leave.LEAVE_ID;
                model.leave_name = username;
                model.Leave_nameid = leaveGuid;
                model.leave_quantity = leave.LEAVE_QUANTITY;
                model.leave_time = leave.LEAVE_TIME;
                model.leave_howmanydays = leave.LEAVE_HOWMANYDAYS;
                model.leave_approver = leave.LEAVE_APPROVER;
                model.leave_cause = leave.LEAVE_CAUSE;
                model.leave_classes = leave.LEAVE_CLASSES;
                model.leave_overname = leave.LEAVE_OVERNAME;
                model.leave_end_day = leave.LEAVE_END_DAY;
                model.leave_begain_day = leave.LEAVE_BEGAIN_DAY;
                model.leave_approverresult = "1";
            }
            #endregion

            return this.View(model);
        }


        /// <summary>
        /// 审批请假
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult LeaveOver(FormCollection collection)
        {
            #region 计算本月时间
            int year = DateTime.Now.Year;//当前年
            int mouth = DateTime.Now.Month;//当前月
            int beforeYear = 0;
            int BeforeMouth = 0;
            if (mouth <= 1)//如果当前月是1月份，那么现在年份-1
            {
                beforeYear = year - 1;
                BeforeMouth = 12;
            }
            else
            {
                beforeYear = year;
                BeforeMouth = mouth - 1;
            }
            DateTime beforeMouthOneDay = Convert.ToDateTime(beforeYear + "-" + mouth + "-" + 1);//本月月的第一天
            DateTime beforeMouthLastDay = Convert.ToDateTime(beforeYear + "-" + mouth + "-" + DateTime.DaysInMonth(year, mouth));//本月的最后一天
            #endregion
            try
            {

                Guid leaveGuid = new Guid(collection["dai_leave_idd"]);
                PROJECT_DESK_LEAVE leave = projectdeskleaveRepository.GetModel(r => r.LEAVE_ID == leaveGuid).FirstOrDefault();//判断传进来的ID是否和当前ID一致
                Guid id = leave.Leave_NAMEID;
                var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();

                Guid ID = leave.Leave_NAMEID;
                //查出符合本月的，登录者的所有请假的集合个数
                List<PROJECT_DESK_LEAVE> x = projectdeskleaveRepository.GetModel(r => r.Leave_NAMEID == ID && r.LEAVE_TIME > beforeMouthOneDay && r.LEAVE_TIME <= beforeMouthLastDay).ToList();
                PROJECT_DESK_LEAVE model = new PROJECT_DESK_LEAVE();
                {
                    model.LEAVE_ID = leave.LEAVE_ID;
                    model.Leave_NAMEID = leave.Leave_NAMEID; ;
                    model.LEAVE_OVERNAME = leave.LEAVE_OVERNAME;
                    model.LEAVE_HOWMANYDAYS = leave.LEAVE_HOWMANYDAYS;
                    model.LEAVE_END_DAY = leave.LEAVE_END_DAY;
                    model.LEAVE_QUANTITY = x.Count + 1;
                    model.LEAVE_TIME = leave.LEAVE_TIME;
                    model.LEAVE_CLASSES = leave.LEAVE_CLASSES;
                    model.LEAVE_CAUSE = leave.LEAVE_CAUSE;
                    model.LEAVE_BEGAIN_DAY = leave.LEAVE_BEGAIN_DAY;
                    model.LEAVE_APPROVER = leave.LEAVE_APPROVER;
                    model.LEAVE_APPROVERRESULT = collection["select_LeaveStatus"];

                }

                projectdeskleaveRepository.Update(model);
                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flagInfo = "审批成功！", flag = "True" });
            }
            catch (Exception ex)
            {

                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", flag = "False", flagInfo = "审批失败！" + ex.Message });
            }


        }










        /// <summary>
        /// 修改请假状态
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult UpdatLeave(FormCollection collection)
        {
            Guid projectId = new Guid(collection["tb_leave_id"]);

            try
            {
                PROJECT_DESK_LEAVE pro = projectdeskleaveRepository.GetModel(r => r.LEAVE_ID == projectId).FirstOrDefault();

                pro.LEAVE_APPROVERRESULT = collection["select_LeaveStatus"];
                projectdeskleaveRepository.Update(pro);
                return RedirectToAction("Leave", "Leave", new { area = "DepartmentArea", projectId = projectId, flag = "True", flagInfo = "项目状态编辑完成！" });

            }
            catch (Exception ex)
            {
                return RedirectToAction("Leave", "Leave", new { aarea = "DepartmentArea", projectId = projectId, info = ex.Message });
            }


        }




        /// <summary>
        /// ajax 获取一条请假信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult LeaveUpdat(Guid roleId)
        {
            ProjectDeskLeaveViewModel model = new ProjectDeskLeaveViewModel();
            PROJECT_DESK_LEAVE role = projectdeskleaveRepository.GetModel(r => r.LEAVE_ID == roleId).FirstOrDefault();
             string name = userRepository.GetModel(r => r.USER_ID == role.Leave_NAMEID).FirstOrDefault().DISPLAY_NAME;
            model.leave_approver = role.LEAVE_APPROVER;
            model.leave_cause = role.LEAVE_CAUSE;
            model.leave_classes = role.LEAVE_CLASSES;
            model.leave_howmanydays = role.LEAVE_HOWMANYDAYS;
            model.leave_id = role.LEAVE_ID;
            model.leave_time = role.LEAVE_TIME;
            model.leave_day = role.LEAVE_BEGAIN_DAY.ToString("yyyy-MM-dd") + "—" + role.LEAVE_END_DAY.ToString("yyyy-MM-dd");
            model.leave_name = name;
         
            //model.leave_begain_day = role.LEAVE_BEGAIN_DAY;
            //model.leave_end_day = role.LEAVE_END_DAY;
            return Json(model);
        }


        /// <summary>
        /// ajax 删除一条请假信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult documentDelete(Guid roleId)
        {

            ProjectDeskLeaveViewModel model = new ProjectDeskLeaveViewModel();
            PROJECT_DESK_LEAVE role = projectdeskleaveRepository.GetModel(r => r.LEAVE_ID == roleId).FirstOrDefault();
            model.leave_id = role.LEAVE_ID;
            return Json(model);
        }



        /// <summary>
        /// 日历的计算
        /// </summary>
        /// <param name="BTime"></param>
        /// <param name="DTime"></param>
        /// <returns></returns>
        public JsonResult JiSuan(DateTime BTime, DateTime DTime)
        {
            #region 计算请假工作日
            ProjectDeskLeaveViewModel model = new ProjectDeskLeaveViewModel();
            DateTime Bday = Convert.ToDateTime(BTime);
            DateTime Dday = Convert.ToDateTime(DTime);
            if (Dday.Year == Bday.Year)//起止日期的年是同一年
            {
                if (Bday.Month == Dday.Month)//相同月份
                {
                    model.day = (Dday.Day - Bday.Day) + 1;
                }
                else if (Dday.Month - Bday.Month == 1)//相邻月份
                {
                    model.day = ((DateTime.DaysInMonth(Bday.Year, Bday.Month) - Bday.Day) + 1) + Dday.Day;
                }
                else if (Dday.Month - Bday.Month > 1)//超过一个月以上
                {
                    int DAY = 0;
                    int DAYY = 0;
                    for (int i = 0; i < (Dday.Month - Bday.Month); i++)
                    {
                        if (Bday.Month + i == Bday.Month)
                        {
                            DAY = DateTime.DaysInMonth(Bday.Year, (Bday.Month + i)) - Bday.Day + 1;
                        }
                        else
                        {
                            DAY = DateTime.DaysInMonth(Bday.Year, (Bday.Month + i));
                        }
                        DAYY += DAY;
                    }
                    model.day = DAYY + Dday.Day;
                }
            }
            else if (Dday.Year - Bday.Year == 1)//起止日期的年是相邻一年
            {
                int D_YearDay = 0;//结束休假那年的时间
                int D_yearDay = 0;
                int B_YearDay = 0;//开始休假到年底的时间
                int B_yearDay = 0;
                for (int i = 0; i <= (12 - Bday.Month); i++)
                {
                    if (Bday.Month + i == Bday.Month)
                    {
                        B_yearDay = DateTime.DaysInMonth(Bday.Year, (Bday.Month + i)) - Bday.Day + 1;
                    }
                    else
                    {
                        B_yearDay = DateTime.DaysInMonth(Bday.Year, (Bday.Month + i));
                    }
                    B_YearDay += B_yearDay;
                }
                for (int i = 0; i <= (Dday.Month - 1); i++)
                {
                    if (Dday.Month - i == Dday.Month)
                    {
                        D_yearDay = Dday.Day;
                    }
                    else
                    {
                        D_yearDay = DateTime.DaysInMonth(Dday.Year, (Dday.Month - i));
                    }
                    D_YearDay += D_yearDay;
                }

                model.day = D_YearDay + B_YearDay;
            }
            else if (Dday.Year - Bday.Year > 1)//起止日期相差两年以上
            {
                int B_YearDay = 0;
                int B_yearDay = 0;
                int D_YearDay = 0;
                int D_yearDay = 0;
                int Z_yer = 0;
                int Z_Yer = 0;
                for (int i = 0; i < Dday.Year - Bday.Year + 1; i++)
                {
                    if (Bday.Year + i == Bday.Year)//起始的那年(第一年)
                    {

                        for (int x = 0; x <= (12 - Bday.Month); x++)
                        {
                            if (Bday.Month + x == Bday.Month)
                            {
                                B_yearDay = DateTime.DaysInMonth(Bday.Year, (Bday.Month + x)) - Bday.Day + 1;
                            }
                            else
                            {
                                B_yearDay = DateTime.DaysInMonth(Bday.Year, (Bday.Month + x));
                            }
                            B_YearDay += B_yearDay;
                        }
                    }
                    else if (Bday.Year + i == Dday.Year)//结束那一年
                    {

                        for (int y = 0; y <= (Dday.Month - 1); y++)
                        {
                            if (Dday.Month - y == Dday.Month)
                            {
                                D_yearDay = Dday.Day;
                            }
                            else
                            {
                                D_yearDay = DateTime.DaysInMonth(Dday.Year, (Dday.Month - y));
                            }
                            D_YearDay += D_yearDay;
                        }
                    }
                    else if (Bday.Year + i != Bday.Year && Bday.Year + i != Dday.Year)//中间那些整年
                    {
                        for (int z = 1; z <= 12; z++)
                        {
                            Z_yer += DateTime.DaysInMonth(Bday.Year + i, z);
                        }
                        Z_Yer = Z_yer;
                    }
                }
                model.day = D_YearDay + B_YearDay + Z_Yer;
            }
            return Json(model);

            #endregion
        }





        /// <summary>
        /// 全员请假查询ajax
        /// </summary>
        /// <param name="NameId"></param>
        /// <param name="BTime"></param>
        /// <param name="DTime"></param>
        /// <returns></returns>
        public JsonResult SelcetS(string NameId, DateTime BTime, DateTime DTime)
        {
         
            List<ProjectDeskLeaveViewModel> list = new List<ProjectDeskLeaveViewModel>();
            List<PROJECT_DESK_LEAVE> model = new List<PROJECT_DESK_LEAVE>();
            if (NameId != "1")
            {
                Guid NameID = new Guid(NameId);
                model = projectdeskleaveRepository.GetModel(r => (r.Leave_NAMEID == NameID && r.LEAVE_BEGAIN_DAY >= BTime && r.LEAVE_BEGAIN_DAY <= DTime && r.LEAVE_APPROVERRESULT == "1")
                    || (r.Leave_NAMEID == NameID && r.LEAVE_BEGAIN_DAY <= BTime && r.LEAVE_END_DAY >= DTime && r.LEAVE_APPROVERRESULT == "1")
                    || (r.Leave_NAMEID == NameID && r.LEAVE_END_DAY >= BTime && r.LEAVE_END_DAY <= DTime) && r.LEAVE_APPROVERRESULT == "1").OrderByDescending(r => r.LEAVE_TIME).ToList();
            }
            if (NameId == "1")
            {
                model = projectdeskleaveRepository.GetModel(r => (r.LEAVE_BEGAIN_DAY >= BTime && r.LEAVE_BEGAIN_DAY <= DTime && r.LEAVE_APPROVERRESULT == "1")
                    || (r.LEAVE_BEGAIN_DAY <= BTime && r.LEAVE_END_DAY >= DTime && r.LEAVE_APPROVERRESULT == "1")
                    || (r.LEAVE_END_DAY >= BTime && r.LEAVE_END_DAY <= DTime) && r.LEAVE_APPROVERRESULT == "1").OrderByDescending(r => r.LEAVE_TIME).ToList();
            }
            if (model.Count > 0)
            {
                foreach (PROJECT_DESK_LEAVE x in model)
                {
                    ProjectDeskLeaveViewModel pl = new ProjectDeskLeaveViewModel();
                    
                    string name = userRepository.GetModel(r => r.USER_ID == x.Leave_NAMEID).FirstOrDefault().DISPLAY_NAME;
                    pl.leave_name = name;
                    pl.leave_id = x.LEAVE_ID;
                    pl.leave_approver = x.LEAVE_APPROVER;
                    if (x.LEAVE_APPROVERRESULT == "1")
                    {
                        pl.leave_approverresult = "通过";
                    }
                    pl.leave_begain_day = x.LEAVE_BEGAIN_DAY;
                    pl.leave_cause = x.LEAVE_CAUSE;
                    pl.leave_classes = x.LEAVE_CLASSES;
                    pl.leave_day = x.LEAVE_BEGAIN_DAY.ToString("yyyy-MM-dd") + "—" + x.LEAVE_END_DAY.ToString("yyyy-MM-dd");
                    pl.leave_end_day = x.LEAVE_END_DAY;
                    pl.leave_howmanydays = x.LEAVE_HOWMANYDAYS;
                    pl.Leave_nameid = x.Leave_NAMEID;
                    pl.leave_overname = x.LEAVE_OVERNAME;
                    pl.leave_quantity = x.LEAVE_QUANTITY;
                    pl.leave_time =x.LEAVE_TIME;
                    pl.leave_time_selcet = x.LEAVE_TIME.ToString("yyyy-MM-dd");
                    list.Add(pl);
                }
            }



            return Json(list);
        }


    }
}








